package com.hzw.net.manager

import android.security.KeyPairGeneratorSpec
import android.security.KeyStoreParameter
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import com.hzw.core.ctx.appCtx
import com.hzw.core.log.logE
import com.hzw.core.store.DataPreferences
import com.hzw.net.utils.RSAUtils
import java.security.*
import javax.crypto.KeyGenerator

/**
 * 秘钥管理
 */
object KeyStorageManager {

    private const val KEY_SERVER_PUBLIC_KEY = "KEY_SERVER_PUBLIC_KEY"

    private const val RSA = "RSA"

    private const val AndroidKeyStore = "AndroidKeyStore"
    private const val KeyStoreAlias = "HStore"
    private const val KeySize = 1024


    private fun getStore(): KeyPair {
        val keyStore = KeyStore.getInstance(AndroidKeyStore).apply {
            load(null)
        }
        if (keyStore.containsAlias(KeyStoreAlias)) {
            return keyStore.getKey(KeyStoreAlias, null) as KeyPair
        }

        val keyPairGenerator = KeyPairGenerator.getInstance(RSA, AndroidKeyStore)
        val kps = if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            KeyGenParameterSpec.Builder(
                KeyStoreAlias,
                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
            ).run {
                setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                setKeySize(KeySize)
                build()
            }

        } else {
            KeyPairGeneratorSpec.Builder(appCtx).run {
                setAlias(KeyStoreAlias)
                setKeySize(KeySize)
                build()
            }
        }
        keyPairGenerator.initialize(kps)
        return keyPairGenerator.genKeyPair()
    }

    fun storageServerPublicKey(publicKeyString: String) {
        DataPreferences.putString(KEY_SERVER_PUBLIC_KEY, publicKeyString)
    }

    fun getServerPublicKeyString(): String {
        return DataPreferences.getString(KEY_SERVER_PUBLIC_KEY, "")
    }

    fun getClientPublicKeyString(): String {
        val keyPair = getStore()
        return RSAUtils.getPublicKeyStandardStringForSend(keyPair.public)
    }

    fun getClientPrivateKey(): PrivateKey? {
        val keyPair = getStore()
        return keyPair.private
    }
}